﻿using Hangjing.Common;
using Newtonsoft.Json;
using Newtonsoft;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Hangjing.EleAPIV2
{
    /// <summary>
    /// 饿了么授权
    /// </summary>
    public class ELEAuth
    {
        protected HttpContext context;
        public string code = "";//用于获取openid

        /// <summary>
        /// 参数列表
        /// </summary>
        protected Hashtable parameters;

        /// <summary>
        /// 计算签名的参数列表
        /// </summary>
        protected Hashtable singparameters;


        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="callbackurl"></param>
        public ELEAuth(HttpContext _context)
        {
            context = _context;
            parameters = new Hashtable();
            singparameters = new Hashtable();
        }

        /// <summary>
        /// 返回授权url
        /// </summary>
        /// <param name="shopid"></param>
        /// <returns></returns>
        public string GetAuthURL(int shopid)
        {
            string callbackurl = appconfig.authcallbackURL;
            string OAuthurl = appconfig.authurl + "?response_type=code&client_id=" + Hangjing.EleAPIV2.appconfig.Key + "&redirect_uri=" + context.Server.UrlEncode(Hangjing.EleAPIV2.appconfig.authcallbackURL) + "&state=" + shopid + "&scope=all";
            return OAuthurl;
        }

        public access_tokenInfo getToken()
        {
            access_tokenInfo token = new access_tokenInfo();

            parameters.Add("grant_type", "authorization_code");
            parameters.Add("code", context.Request["code"]);
            parameters.Add("redirect_uri", appconfig.authcallbackURL);
            parameters.Add("client_id", appconfig.Key);

            string Authorization = appconfig.Key + ":" + appconfig.Secret;
            byte[] bytes = Encoding.UTF8.GetBytes(Authorization);

            HttpItem objHttpItem = new HttpItem()
            {
                Authorization = "Basic " + Convert.ToBase64String(bytes),
                URL = appconfig.tokenurl,
                Encoding = "utf-8",
                Method = "POST",
                Postdata = getPostDatan()
            };

            HttpHelper objhttp = new HttpHelper();
            objhttp.isToLower = false;


            Hangjing.AppLog.AppLog.Info("getToken:" + getPostDatan() + "\r\nurl=" + appconfig.tokenurl + "\r\nAuthorization=" + Convert.ToBase64String(bytes));

            string returnmsg = objhttp.GetHtml(objHttpItem);

            Hangjing.AppLog.AppLog.Info("getToken:" + getPostDatan() + "\r\nmsg=" + returnmsg + "\r\nAuthorization=" + Convert.ToBase64String(bytes));

            token = JsonConvert.DeserializeObject<access_tokenInfo>(returnmsg);
            if (token != null)
            {
                token.shopid = Convert.ToInt32(context.Request["state"]);
            }

            return token;
        }

        public access_tokenInfo refreshToken(int shopid,string refresh_token)
        {
            access_tokenInfo token = new access_tokenInfo();

            parameters.Add("grant_type", "refresh_token");
            parameters.Add("refresh_token", refresh_token);

            string Authorization = appconfig.Key + ":" + appconfig.Secret;
            byte[] bytes = Encoding.UTF8.GetBytes(Authorization);

            HttpItem objHttpItem = new HttpItem()
            {
                Authorization = "Basic " + Convert.ToBase64String(bytes),
                URL = appconfig.tokenurl,
                Encoding = "utf-8",
                Method = "POST",
                Postdata = getPostDatan()
            };

            HttpHelper objhttp = new HttpHelper();
            objhttp.isToLower = false;

            string returnmsg = objhttp.GetHtml(objHttpItem);

            Hangjing.AppLog.AppLog.Info("getToken:" + getPostDatan() + "\r\nmsg=" + returnmsg + "\r\nAuthorization=" + Convert.ToBase64String(bytes));

            token = JsonConvert.DeserializeObject<access_tokenInfo>(returnmsg);
            if (token != null)
            {
                token.shopid = shopid;
            }

            return token;
        }


        /// <summary>
        /// 根据参数列表，生成post 数据
        /// </summary>
        /// <returns></returns>
        public string getPostDatan()
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();

            foreach (string k in akeys)
            {
                string v = HttpUtility.UrlEncode((string)parameters[k], Encoding.UTF8);
                if (null != v && "".CompareTo(v) != 0
                       && "sig".CompareTo(k) != 0)
                {
                    if (sb.Length == 0)
                    {
                        sb.Append(k + "=" + v);
                    }
                    else
                    {
                        sb.Append("&" + k + "=" + v);
                    }
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 根据参数列表，生成post 数据
        /// </summary>
        /// <returns></returns>
        public string getPostJSONData()
        {
           
            ArrayList akeys = new ArrayList(parameters.Keys);
            akeys.Sort();


            return JsonConvert.SerializeObject(parameters); ;
        }

        /// <summary>
        /// 签名
        /// </summary>
        /// <returns></returns>
        public string createMD5Sign(string action, string token)
        {
            StringBuilder sb = new StringBuilder();
            ArrayList akeys = new ArrayList();

            foreach (var item in singparameters.Keys)
            {
                akeys.Add(item + "=" + JsonConvert.SerializeObject(singparameters[item]) + "");
            }
            akeys.Sort();

            foreach (string k in akeys)
            {
                sb.Append(k);
            }

            string signstep = action + token + sb.ToString() + appconfig.Secret;

            Hangjing.AppLog.AppLog.Info("createMD5Sign:oldsignstep=" + signstep);

            signstep = Utils.MD5(signstep).ToUpper();

            Hangjing.AppLog.AppLog.Info("createMD5Sign:signstep=" + signstep);

            return signstep;
        }

    }
}
